package Timer;

import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.Queue;

public class MyTimer {
    private final PriorityQueue<Task> queue = new PriorityQueue<>();
    public final Object lock = new Object();
    public void schedule(Runnable runnable,long time){
        synchronized (lock){
            Task task = new Task(runnable,time);
            System.out.println(Thread.currentThread().getName() + "==> 成功压入队列中");
            queue.offer(task);
            lock.notifyAll();
        }
    }

    public MyTimer(){
        Thread t = new Thread(()->{
           while (true) {
               synchronized (lock) {

                   while (queue.isEmpty()) {
                       try {

                           System.out.println(Thread.currentThread().getName()+"==>队列中没有元素，正在等待中");
                           lock.wait();
                       } catch (InterruptedException e) {
                           throw new RuntimeException(e);
                       }
                   }

                   Task task = queue.peek();
                   long currentTime = System.currentTimeMillis();
                   if (task.time <= System.currentTimeMillis()) {
                       queue.poll();
                       task.runnable.run();
                   } else {
                       try {
                           lock.wait(task.time - currentTime);
                           System.out.println("还有 ==>" + (task.time - currentTime) );
                       } catch (InterruptedException e) {
                           throw new RuntimeException(e);
                       }
                   }
               }
           }
        });
        t.start();
    }

}

class Task implements Comparable<Task>{
    public Runnable runnable;
    public long time;

    public Task(Runnable runnable,long time){
        this.runnable = runnable;
        this.time = time + System.currentTimeMillis();
    }

    @Override
    public int compareTo(Task o) {
        return  (int) (this.time - o.time);
    }

}
